<?php
/**
 * Created by PhpStorm.
 * User: von
 * Date: 2017/11/28
 * Time: 18:24
 */
namespace backend\models;

use common\models\Package;
use common\models\PackageInitiation;
use common\models\Responses;
use common\models\UserModel;
use yii\db\ActiveRecord;

class MyPackage extends ActiveRecord {
    /*
     * 获取我参与的资产包
     * @params: $count 默认为0 不获取查询数据总数  1获取查询数据总数
     *$packageState 资产包状态//1无、2启动尽调、3已立项、4已评估、5已受让、6待跟进、
     */
    public static function getMyPackageData($conditions=null,$count=0,$state = 0,$pages=0){
        //----------1.资产包状态----------
        if ($state == 0){
            if (!empty($conditions['packageState']) && $conditions['packageState']!=123){
                $packageState = $conditions['packageState'];
                $where_packageState = "p.state = $packageState";
            }else{
                $packageState = 0;
                $where_packageState = true;
            }
        }else if($state == 123){
            $where_packageState = [];
        } else{
            $where_packageState =  "p.state = $state";
        }
        //----------2.用户id----------
        if (!empty($conditions['userId'])){
            $userID = $conditions['userId'];
            //-----上级读取下级所有参与资产包信息------start
            $userModel = (new \yii\db\Query())->from(User::tableName())->where(['=','id',$userID])->andWhere(['=','post','BranchManager'])->one();
            if (false){
                $userGroup = (new \yii\db\Query())->from(User::tableName())->where(['=','department',$userModel['department']])->all();
                $userIdArr = [];
                $userIdArrS = [];
                foreach ($userGroup as $k => $v) {
                    $userIdArr[]=$v['id'];
                    $userIdArrS[]=','.$v['id'].',';
                }
                $where_userid =  ['or',['or like','pi.pre_evaluation',$userIdArrS],['or like','pi.leader',$userIdArr],['or like','pi.due_diligence',$userIdArrS],['or like','pi.zongjian',$userIdArrS]];
            }else{
                $where_userid = "pi.pre_evaluation like '%,$userID,%' or pi.leader like '%$userID%'  or pi.leader like '%,$userID,%' or pi.due_diligence like '%,$userID,%' or pi.zongjian like '%,$userID,%' or pi.zongjian='$userID' ";
            }
            //-----上级读取下级所有参与资产包信息------end
        }else{
            $where_userid = true;
            return Responses::response400('重新登录');
        }
        //----------3.关键词----------
        if (!empty($conditions['keywords'])){
            $keywords = $conditions['keywords'];
            //先查找用户
            $leaderID = (new \yii\db\Query())->select('id')->from(UserModel::tableName())->where(['like','realname',$keywords])->all();
            $leaderIDArr = [];
            if (!empty($leaderID)){
                foreach ($leaderID as $k => $v) {
                    $leaderIDArr[$k]=','.$v['id'].',';
                }
            }
            $where_key = ['like','p.title',$keywords];
            $where_key_userId = ['or like','pi.leader',$leaderIDArr];
        }else{
            $where_key = [];
            $where_key_userId = [];
        }
        //是否上传完成1完成 0未完成
        $is_finishedVal = \Yii::$app->params['is_finished'][1]['val'];
        $is_finished = ['=','p.is_finished',$is_finishedVal];
        //排序
        //--2018年3月2日11:01:51 fly  --No--START
        if (!empty($conditions['orderGroup'])){
            switch ($conditions['orderGroup']){
                case 1:
                    $where_order = 'p.title ASC';
                    break;
                case 2:
                    $where_order = 'p.title DESC';
                    break;
                case 3:
                    $where_order = 'p.type ASC';
                    break;
                case 4:
                    $where_order = 'p.type DESC';
                    break;
                case 5:
                    $where_order = 'p.city ASC';
                    break;
                case 6:
                    $where_order = 'p.city DESC';
                    break;
                case 7:
                    $where_order = 'p.principal ASC';
                    break;
                case 8:
                    $where_order = 'p.principal DESC';
                    break;
                case 9:
                    $where_order = 'p.interest ASC';
                    break;
                case 10:
                    $where_order = 'p.interest DESC';
                    break;
                case 11:
                    $where_order = 'p.hushu ASC';
                    break;
                case 12:
                    $where_order = 'p.hushu DESC';
                    break;
                case 13:
                    $where_order = 'pi.leader ASC';
                    break;
                case 14:
                    $where_order = 'pi.leader DESC';
                    break;
                case 15:
                    $where_order = 'p.created_at ASC';
                    break;
                case 16:
                    $where_order = 'p.created_at DESC';
                    break;
                case 17:
                    $where_order = 'p.state ASC';
                    break;
                case 18:
                    $where_order = 'p.state DESC';
                    break;
                default:
                    $where_order = 'p.created_at DESC';
                    break;
            }
        }else{
            $where_order = 'p.created_at DESC';
        }
        //----------------拼装查询条件----------------
        if($count != 0 && $pages == 0){
            $countData = (new \yii\db\Query())->select('count(*) as count')->from("package as p")->leftJoin("package_initiation as pi",'p.id = pi.package_id')->where($where_userid)->andWhere(['or',$where_key,$where_key_userId])->andWhere($where_packageState)->andWhere($is_finished)->groupBy('p.id ')->count('*');
            return  $countData;
        }
        $data = (new \yii\db\Query())->select('*')->from("package as p")->leftJoin("package_initiation as pi",'p.id = pi.package_id')->where($where_userid)->andWhere(['or',$where_key,$where_key_userId])->andWhere($where_packageState)->andWhere($is_finished)->offset($pages->offset)->limit($pages->limit)->groupBy('p.id ')->addOrderBy($where_order)->all();
        //--------------------查询管理员名称--------------------
        if (!empty($data)){
            foreach ($data as $k => $v) {
                $packageUserId = array_filter(explode(',',$v['due_diligence']));
                if (!empty($packageUserId)){
                    $data[$k]['userName'] = (new \yii\db\Query())->select('id,realname,ai.description as description')->from('user as u')->leftJoin('auth_assignment as aa','u.id = aa.user_id')->leftJoin('auth_item as ai','ai.name = u.department')->where(['in','u.id',$packageUserId])->groupBy('aa.user_id')->all();
                }else{
                    $data[$k]['userName'] = [];
                }
            }
        }
        //--------------------查询上传人名称--------------------
        if (!empty($data)){
            foreach ($data as $k => $v) {
                $packageLeaderId = array_filter(explode(',',$v['leader']));
                if (!empty($packageLeaderId)){
                    $data[$k]['LeaderName'] = (new \yii\db\Query())->select('id,realname,ai.description as description')->from('user as u')->leftJoin('auth_assignment as aa','u.id = aa.user_id')->leftJoin('auth_item as ai','ai.name = u.department')->where(['in','u.id',$packageLeaderId])->all();
                }else{
                    $data[$k]['LeaderName'] = [];
                }
            }
        }
        //---------------省份id转换------------------------
        if (!empty($data)){
            foreach ($data as $k => $v) {
                $provinceID = $v['province'];
                $cityID = $v['city'];
                if (!empty($provinceID)){
                    $data[$k]['provinceName'] = (new \yii\db\Query())->select('title')->from(Country::tableName())->where(['=', 'id', $provinceID])->one();
                }else {
                    $data[$k]['provinceName']['title'] = '';
                }

                if (!empty($cityID)) {
                    $data[$k]['cityName'] = (new \yii\db\Query())->select('title')->from(Country::tableName())->where(['=', 'id', $cityID])->one();
                } else {
                    $data[$k]['cityName']['title'] = '';
                }

            }
        }
//        var_dump($data);die;
        return  $data;
    }
    /*
     * 我上传的资产包
       *   @params: $count 默认为0 不获取查询数据总数  1获取查询数据总数
     */
    public static function getUploadMyPackageData($conditions=null,$count=0,$state = 0,$pages=0){
        //----------1.资产包状态----------
        if ($state == 0) {
            if (!empty($conditions['packageState']) && $count == 0 && $conditions['packageState']!=123) {
                $packageState = $conditions['packageState'];
                $where_packageState = "p.state = $packageState";
            } else {
                $packageState = 0;
                $where_packageState = true;
            }
        }else if($state == 123){
            $where_packageState = true;
        } else{
            $where_packageState =  "p.state = $state";
        }
        //----------2.用户id----------
        if (!empty($conditions['userId'])){
            $userID = $conditions['userId'];
            $where_userid = "p.owner = $userID";
        }else{
            $where_userid = true;
            return Responses::response400('重新登录');
        }
        //----------3.关键词----------
        if (!empty($conditions['keywords'])){
            $keywords = $conditions['keywords'];
            //先查找用户
            $leaderID = (new \yii\db\Query())->select('id')->from(UserModel::tableName())->where(['like','realname',$keywords])->all();
            $leaderIDArr = [];
            if (!empty($leaderID)){
                foreach ($leaderID as $k => $v) {
                    $leaderIDArr[$k]=','.$v['id'].',';
                }
            }
            $where_key = ['like','p.title',$keywords];
            $where_key_userId = ['or like','pi.leader',$leaderIDArr];
        }else{
            $where_key = [];
            $where_key_userId = [];
        }

        //是否上传完成1完成 0未完成
        $is_finishedVal = \Yii::$app->params['is_finished'][1]['val'];
        $is_finished = ['=','p.is_finished',$is_finishedVal];
        //排序
        //--2018年3月2日11:01:51 fly  --No--START
        if (!empty($conditions['orderGroup'])){
            switch ($conditions['orderGroup']){
                case 1:
                    $where_order = 'p.title ASC';
                    break;
                case 2:
                    $where_order = 'p.title DESC';
                    break;
                case 3:
                    $where_order = 'p.type ASC';
                    break;
                case 4:
                    $where_order = 'p.type DESC';
                    break;
                case 5:
                    $where_order = 'p.city ASC';
                    break;
                case 6:
                    $where_order = 'p.city DESC';
                    break;
                case 7:
                    $where_order = 'p.principal ASC';
                    break;
                case 8:
                    $where_order = 'p.principal DESC';
                    break;
                case 9:
                    $where_order = 'p.interest ASC';
                    break;
                case 10:
                    $where_order = 'p.interest DESC';
                    break;
                case 11:
                    $where_order = 'p.hushu ASC';
                    break;
                case 12:
                    $where_order = 'p.hushu DESC';
                    break;
                case 13:
                    $where_order = 'pi.leader ASC';
                    break;
                case 14:
                    $where_order = 'pi.leader DESC';
                    break;
                case 15:
                    $where_order = 'p.created_at ASC';
                    break;
                case 16:
                    $where_order = 'p.created_at DESC';
                    break;
                case 17:
                    $where_order = 'p.state ASC';
                    break;
                case 18:
                    $where_order = 'p.state DESC';
                    break;
                default:
                    $where_order = 'p.created_at DESC';
                    break;
            }
        }else{
            $where_order = 'p.created_at DESC';
        }
        //----------------拼装查询条件----------------
        if($count != 0){
            $countData = (new \yii\db\Query())->select('count(*) as count')->from("package as p")->leftJoin("package_initiation as pi",'p.id = pi.package_id')->where($where_userid)->andWhere($is_finished)->andWhere($where_packageState)->andWhere(['or',$where_key,$where_key_userId])->groupBy('p.id ')->count('*');
            return  $countData;
        }
        $data = (new \yii\db\Query())->select('*,p.id')->from("package as p")->leftJoin("package_initiation as pi",'p.id = pi.package_id')->where($where_userid)->andWhere($is_finished)->andWhere($where_packageState)->andWhere(['or',$where_key,$where_key_userId])->offset($pages->offset)->limit($pages->limit)->groupBy('p.id ')->addOrderBy($where_order)->all();
        //--------------------查询管理员名称--------------------
        if (!empty($data)){
            foreach ($data as $k => $v) {
                $packageUserId = array_filter(explode(',',$v['due_diligence']));
                if (!empty($packageUserId)){
                    $data[$k]['userName'] = (new \yii\db\Query())->select('id,realname,ai.description as description')->from('user as u')->leftJoin('auth_assignment as aa','u.id = aa.user_id')->leftJoin('auth_item as ai','ai.name = u.department')->where(['in','id',$packageUserId])->groupBy('aa.user_id')->all();
                }else{
                    $data[$k]['userName'] = [];
                }
            }
        }
        //--------------------查询上传人名称--------------------
        if (!empty($data)){
            foreach ($data as $k => $v) {
                $packageLeaderId = array_filter(explode(',',$v['leader']));
                if (!empty($packageLeaderId)){
                    $data[$k]['LeaderName'] = (new \yii\db\Query())->select('id,realname,ai.description as description')->from('user as u')->leftJoin('auth_assignment as aa','u.id = aa.user_id')->leftJoin('auth_item as ai','ai.name = u.department')->where(['in','id',$packageLeaderId])->all();
                }else{
                    $data[$k]['LeaderName'] = [];
                }
            }
        }
        //---------------省份id转换------------------------
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $provinceID = $v['province'];
                $cityID = $v['city'];
                if (!empty($provinceID)){
                    $data[$k]['provinceName'] = (new \yii\db\Query())->select('title')->from(Country::tableName())->where(['=', 'id', $provinceID])->one();
                }else {
                    $data[$k]['provinceName']['title'] = '';
                }

                if (!empty($cityID)) {
                    $data[$k]['cityName'] = (new \yii\db\Query())->select('title')->from(Country::tableName())->where(['=', 'id', $cityID])->one();
                } else {
                    $data[$k]['cityName']['title'] = '';
                }
            }
        }
        return  $data;
    }
    /*
  * 我关注的资产包
    *   @params: $count 默认为0 不获取查询数据总数  1获取查询数据总数
  */
    public static function getMyFollowPackageData($conditions=null,$count=0,$state = 0,$pages=0)
    {
        //----------1.资产包状态----------
        if ($state == 0) {
            if (!empty($conditions['packageState']) && $conditions['packageState']!=123) {
                $packageState = $conditions['packageState'];
                $where_packageState = "p.state = $packageState";
            } else {
                $packageState = 0;
                $where_packageState = true;
            }
        }else if($state == 123){
            $where_packageState = true;
        } else{
            $where_packageState =  "p.state = $state";
        }
        //----------2.用户id----------
        if (!empty($conditions['userId'])){
            $userID = $conditions['userId'];
            $where_userid = "pl.user_id = $userID";
        }else{
            $where_userid = true;
            return Responses::response400('重新登录');
        }
        //----------3.关键词----------
        if (!empty($conditions['keywords'])){
            $keywords = $conditions['keywords'];
            //先查找用户
            $leaderID = (new \yii\db\Query())->select('id')->from(UserModel::tableName())->where(['like','realname',$keywords])->all();
            $leaderIDArr = [];
            if (!empty($leaderID)){
                foreach ($leaderID as $k => $v) {
                    $leaderIDArr[$k]=','.$v['id'].',';
                }
            }
            $where_key = ['like','p.title',$keywords];
            $where_key_userId = ['or like','pi.leader',$leaderIDArr];
        }else{
            $where_key = [];
            $where_key_userId = [];
        }
        //是否上传完成1完成 0未完成
        $is_finishedVal = \Yii::$app->params['is_finished'][1]['val'];
        $is_finished = ['=','p.is_finished',$is_finishedVal];
        //排序
        //--2018年3月2日11:01:51 fly  --No--START
        if (!empty($conditions['orderGroup'])){
            switch ($conditions['orderGroup']){
                case 1:
                    $where_order = 'p.title ASC';
                    break;
                case 2:
                    $where_order = 'p.title DESC';
                    break;
                case 9:
                    $where_order = 'p.city ASC';
                    break;
                case 10:
                    $where_order = 'p.city DESC';
                    break;
                case 3:
                    $where_order = 'p.principal ASC';
                    break;
                case 4:
                    $where_order = 'p.principal DESC';
                    break;
                case 5:
                    $where_order = 'p.interest ASC';
                    break;
                case 6:
                    $where_order = 'p.interest DESC';
                    break;
                case 7:
                    $where_order = 'p.hushu ASC';
                    break;
                case 8:
                    $where_order = 'p.hushu DESC';
                    break;
                case 11:
                    $where_order = 'pi.leader ASC';
                    break;
                case 12:
                    $where_order = 'pi.leader DESC';
                    break;
                case 13:
                    $where_order = 'p.created_at ASC';
                    break;
                case 14:
                    $where_order = 'p.created_at DESC';
                    break;
                case 15:
                    $where_order = 'p.state ASC';
                    break;
                case 16:
                    $where_order = 'p.state DESC';
                    break;
                case 17:
                    $where_order = 'pi.due_diligence ASC';
                    break;
                case 18:
                    $where_order = 'pi.due_diligence DESC';
                    break;
                default:
                    $where_order = 'p.created_at DESC';
                    break;
            }
        }else{
            $where_order = 'p.created_at DESC';
        }
        //----------------拼装查询条件----------------
//        select * from package_like as pl
//left join package as p on p.owner = 1 and pl.package_id = p.id
//left join package_initiation as pi on p.id = pi.package_id
//where pl.user_id = 1 and (pi.leader like '%四大四大%' or p.title like '%四大四大%')  and p.state= 1;
        if($count != 0){
            $countData = (new \yii\db\Query())->select('count(*) as count')->from("package_like as pl")->leftJoin("package as p",' pl.package_id = p.id')->leftJoin("package_initiation as pi",'p.id = pi.package_id')->where($where_userid)->andWhere(['or',$where_key,$where_key_userId])->andWhere($is_finished)->andWhere($where_packageState)->groupBy('p.id ')->count('*');
            return  $countData;
        }
        $data = (new \yii\db\Query())->select('*,p.id,pl.package_id')->from("package_like as pl")->leftJoin("package as p",' pl.package_id = p.id')->leftJoin("package_initiation as pi",'p.id = pi.package_id')->where($where_userid)->andWhere(['or',$where_key,$where_key_userId])->andWhere($is_finished)->andWhere($where_packageState)->offset($pages->offset)->limit($pages->limit)->groupBy('p.id ')->addOrderBy($where_order)->all();
        //--------------------查询管理员名称--------------------
        if (!empty($data)){
            foreach ($data as $k => $v) {
                $packageUserId = array_filter(explode(',',$v['due_diligence']));
                if (!empty($packageUserId)){
                    $data[$k]['userName'] = (new \yii\db\Query())->select('id,realname,ai.description as description')->from('user as u')->leftJoin('auth_assignment as aa','u.id = aa.user_id')->leftJoin('auth_item as ai','ai.name = u.department')->where(['in','id',$packageUserId])->groupBy('aa.user_id')->all();

                }else{
                    $data[$k]['userName'] = [];
                }
            }
        }
        //--------------------查询上传人名称--------------------
        if (!empty($data)){
            foreach ($data as $k => $v) {
                $packageLeaderId = array_filter(explode(',',$v['leader']));
                if (!empty($packageLeaderId)){
                    $data[$k]['LeaderName'] = (new \yii\db\Query())->select('id,realname,ai.description as description')->from('user as u')->leftJoin('auth_assignment as aa','u.id = aa.user_id')->leftJoin('auth_item as ai','ai.name = u.department')->where(['in','u.id',$packageLeaderId])->all();
                }else{
                    $data[$k]['LeaderName'] = [];
                }
            }
        }
        //---------------省份id转换------------------------
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $provinceID = $v['province'];
                $cityID = $v['city'];
                if (!empty($provinceID)){
                    $data[$k]['provinceName'] = (new \yii\db\Query())->select('title')->from(Country::tableName())->where(['=', 'id', $provinceID])->one();
                }else {
                    $data[$k]['provinceName']['title'] = '';
                }

                if (!empty($cityID)) {
                    $data[$k]['cityName'] = (new \yii\db\Query())->select('title')->from(Country::tableName())->where(['=', 'id', $cityID])->one();
                } else {
                    $data[$k]['cityName']['title'] = '';
                }
            }
        }
        return  $data;
    }
}
